package com.weepal.pavement.mqtt.demo.controller;

import com.weepal.pavement.mqtt.demo.config.dataSource.NacosDynamicsDataSources;
import com.weepal.pavement.mqtt.demo.config.dataSource.DynamicsDataSource;
import com.weepal.pavement.mqtt.demo.message.MqttSender;
import com.weepal.pavement.mqtt.demo.util.test;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("sendMessage")
@Slf4j
public class SendMessageController {

    @Autowired
    private MqttSender sender;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private NacosDynamicsDataSources configTest3;

    @PostMapping("send")
    public void send(@RequestParam("mqttId") String mqttId, @RequestParam("topic") String topic, @RequestParam("message") String message) {
        sender.sendMessage(mqttId, topic, message.getBytes());
    }

    @GetMapping("sendMQ")
    public void sendMQ(String msg) {
        rabbitTemplate.convertSendAndReceive("wjjTest", "wjj1", msg);
    }

    @GetMapping("hex2dec")
    public String hex2dec(String x, int type) {
        return test.hex2dec(x, type);
    }

    @GetMapping("getConfig3")
    public String getConfig3() {
        return configTest3.foo();
    }

    //动态配置数据源
    @Autowired
    private ApplicationContext applicationContext;

    @GetMapping("resetSources")
    public void resetSources() {
        DynamicsDataSource dynaDatasource = applicationContext.getBean("dynaDatasource", DynamicsDataSource.class);
        Map<Object, Object> objectObjectMap = configTest3.buildSource();
        dynaDatasource.setTargetDataSources(objectObjectMap);
        dynaDatasource.afterPropertiesSet();
    }
}
